package client.view;

import model.Message;

import client.service.UpdateFriendListManager;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.Socket;
import client.service.UpdateFriendList;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TextField;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundImage;
import javafx.scene.layout.BackgroundPosition;
import javafx.scene.layout.BackgroundRepeat;
import javafx.scene.layout.BackgroundSize;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import model.MsgType;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import java.util.regex.Pattern;
import client.main.*;
import com.google.gson.Gson;
import client.view.MachineChat;
import client.TreeCellRenderer;

//登录成功后的主页面，显示好友列表，未在线好友头像灰色，双击某好友即可打开与其聊天界面,点击退出按钮即可退出登录
public class FriendList extends Stage  {
    private String ownerqq;//本人qq
    private String myName;//本人昵称
    private int userid;   //本人的userid,与账号不同
    private Button btn_min;
    private Button btn_exit;
    private ImageView jbl_leftTop;
    private ImageView jbl_background;
    private final Label jbl_qqName;
    private AnchorPane root;
    private TreeView<String> treeView;
    TreeItem<String> rootNode3;
    TreeItem<String> rootNode;
    TreeItem<String> rootNode2;
    private int index=0;
    private double xOffset = 0;
    private double yOffset = 0;
    private Vector<String> friends = new Vector<String>();
    private Vector<String> rooms = new Vector<String>();
    
    Type hashtableType = new ParameterizedType() {
        public Type[] getActualTypeArguments() {
            return new Type[]{Integer.class, String.class};
        }

        public Type getRawType() {
            return Hashtable.class;
        }

        public Type getOwnerType() {
            return null;
        }
    };
    
    
    Type vectorType = new ParameterizedType() {
        public Type[] getActualTypeArguments() {
            return new Type[]{String.class};
        }

        public Type getRawType() {
            return Vector.class;
        }

        public Type getOwnerType() {
            return null;
        }
    };
    
    
    Type vectorType2 = new ParameterizedType() {
        public Type[] getActualTypeArguments() {
            return new Type[]{Integer.class};
        }

        public Type getRawType() {
            return Vector.class;
        }

        public Type getOwnerType() {
            return null;
        }
    };
    
    
    public FriendList(String name, String owneraccount, Message msg) {
    	    	
        this.initStyle(StageStyle.UNDECORATED);
        this.ownerqq = owneraccount;
        this.myName = name;
        this.userid = msg.getUserID();
        // 初始化界面布局
        root = new AnchorPane();
        root.setPrefSize(340, 660);
        //上半部分背景图
        Image topImg = new Image("file:image/friendlist/beijing.png", 355, 180, false, false);
        jbl_background = new ImageView(topImg);
        root.getChildren().add(jbl_background);

        Image northImg = new Image("file:image/friendlist/biaoti.png", 60, 30, false, false);
        jbl_leftTop = new ImageView(northImg);
        jbl_leftTop.setStyle("-fx-background-color: transparent;");
        root.getChildren().add(jbl_leftTop);

        //右上角最小化按钮
        btn_min = new Button();
        ImageView minView = new ImageView(new Image("file:image/friendlist/fmin.png",30,26,false,false));
        btn_min.setGraphic(minView);
        AnchorPane.setTopAnchor(btn_min, 0.0);
        AnchorPane.setLeftAnchor(btn_min, 283.0);
        btn_min.setStyle("-fx-background-color: transparent;"); // 设置样式
        btn_min.setOnAction(e -> this.setIconified(true));
        root.getChildren().add(btn_min);
        //右上角退出按钮
        btn_exit = new Button();
        ImageView exitView = new ImageView(new Image("file:image/friendlist/fexit.png",30,26,false,false));
        btn_exit.setGraphic(exitView);
        AnchorPane.setTopAnchor(btn_exit, 0.0);
        AnchorPane.setLeftAnchor(btn_exit, 313.0);
        btn_exit.setStyle("-fx-background-color: transparent;"); // 设置样式
        btn_exit.setOnAction(e ->{ sendUnloadMsgToServer();});
        root.getChildren().add(btn_exit);

        //头像列表，用来储存所有头像文件路径
        List<String> avatarList = Arrays.asList(
                "file:image/friendlist/avatar1.jpg",
                "file:image/friendlist/avatar2.jpg",
                "file:image/friendlist/avatar3.jpg",
                "file:image/friendlist/avatar4.jpg",
                "file:image/friendlist/avatar5.jpg"
        );

        ImageView avatar = new ImageView(new Image("file:image/friendlist/avatar1.jpg")); // 默认头像
        avatar.setFitHeight(100);
        avatar.setFitWidth(100);
        avatar.setX(30);
        avatar.setY(45);
        avatar.setStyle("-fx-background-color: transparent;"); // 设置样式

        // 点击更换头像按钮事件处理
        Button changeAvatarBtn = new Button("更换头像");
        AnchorPane.setTopAnchor(changeAvatarBtn, 150.0);
        AnchorPane.setLeftAnchor(changeAvatarBtn, 35.0);
        changeAvatarBtn.setOnAction(e -> {
            index++;
            if(index >= avatarList.size()){
                index = 0;
            }
            // 加载下一张头像并更新显示
            avatar.setImage(new Image(avatarList.get(index)));
        });

        root.getChildren().addAll(changeAvatarBtn,avatar);


        //qq昵称
        jbl_qqName = new Label(" "+myName+"\n"+"("+ownerqq+")");
        jbl_qqName.setStyle("-fx-font-weight: bold;");
        AnchorPane.setTopAnchor(jbl_qqName, 70.0);
        AnchorPane.setLeftAnchor(jbl_qqName, 140.0);
        root.getChildren().add(jbl_qqName);

        // 修改用户名按钮
        Button changeNameBtn = new Button("修改用户信息");
        AnchorPane.setTopAnchor(changeNameBtn, 150.0);
        AnchorPane.setLeftAnchor(changeNameBtn, 115.0);
        changeNameBtn.setOnAction(event -> {
            Name_Pwd_Modify(owneraccount);                        //可能有问题
        });

        root.getChildren().add(changeNameBtn);

        // 添加鼠标按下事件监听器
        root.setOnMousePressed(event -> {
            xOffset = event.getSceneX();
            yOffset = event.getSceneY();
        });

        // 添加鼠标拖拽事件监听器
        root.setOnMouseDragged(event -> {
            this.setX(event.getScreenX() - xOffset);
            this.setY(event.getScreenY() - yOffset);
        });

        //在线状态选择列表
        String[] status = {"在线","隐身"};
        ComboBox<String> online_status = new ComboBox<>(FXCollections.observableArrayList(status));
        online_status.getSelectionModel().select(0);
        online_status.setLayoutX(250);
        online_status.setLayoutY(80);
        root.getChildren().add(online_status);
        online_status.setOnAction(event -> {
            String newStatus = online_status.getValue();
            Message message=new Message();
            message.setUserID(Integer.parseInt(ownerqq));          //可能有问题
            if(newStatus.equals("在线")) {
                message.setType(MsgType.USER_ONLINE);
            }else {
                message.setType(MsgType.USER_HIDE);
            }
            try {
            	 Socket client = new Socket(Client_main.ip, 12345);
	        	 DataOutputStream output = new DataOutputStream(client.getOutputStream());
	        	 Gson gson = new Gson();
	        	 String json = gson.toJson(message);
	        	 output.writeUTF(json);
	        	 output.close();
	        	 client.close();
	        	 
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            System.out.println("用户状态更新为：" + newStatus);
        });
        
        
      //查看好友列表按钮
	    Button look = new Button("查看好友申请");
	    look.setStyle("-fx-background-color: #0099FF; -fx-text-fill: white;");
	    AnchorPane.setTopAnchor(look, 626.0);
	    AnchorPane.setLeftAnchor(look, 10.0);
	    look.setPrefWidth(50.0);
	    look.setPrefHeight(22.0);
	    root.getChildren().add(look);
	  
	    look.setOnAction(e ->{
	    	 UpdateFriendList u = UpdateFriendListManager.getUpdateFriendList(Integer.parseInt(ownerqq));
	    	if(u.getMsg().isEmpty()) {
	    		Alert alert = new Alert(Alert.AlertType.WARNING);
        	    alert.setContentText("没有新的好友申请！");
        	    alert.show();
        	    return;
	    	}else {
	    		FriendRequestPage fp=new FriendRequestPage(u.getMsg(),Integer.parseInt(ownerqq));
	    	}	    	
	    });
	   	    
        //添加好友搜索框
	    TextField content = new TextField();
	    AnchorPane.setTopAnchor(content, 622.0);
	    AnchorPane.setLeftAnchor(content, 70.0);
	    content.setPrefWidth(194.0);
	    content.setPrefHeight(32.0);
	    content.setStyle("-fx-background-color: white;");
	    content.setPromptText("搜索好友或群聊"); //设置提示文字
	    root.getChildren().add(content);

	    //确认申请按钮
	    Button btn_ok = new Button("确定");
	    AnchorPane.setTopAnchor(btn_ok, 626.0);
	    AnchorPane.setLeftAnchor(btn_ok, 285.0);
	    btn_ok.setPrefWidth(50.0);
	    btn_ok.setPrefHeight(22.0);
	    btn_ok.setStyle("-fx-background-color: #0099FF; -fx-text-fill: white;");
	    btn_ok.setOnAction(e -> {
	        String contents = content.getText().trim();//申请人QQ号
	        if(contents.equals("")) {
	            Alert alert = new Alert(Alert.AlertType.WARNING);
	            alert.setContentText("请输入申请人QQ号！");
	            alert.show();
	            return;
	        }
	        if(contents.equals(ownerqq)) {
	            Alert alert = new Alert(Alert.AlertType.WARNING);
	            alert.setContentText("申请人不能是自己！");
	            alert.show();
	            return;
	        }
	        
	        for(String faccount : friends) {
	        	if(contents.equals(faccount)) {
	        		Alert alert = new Alert(Alert.AlertType.WARNING);
		            alert.setContentText("已经成为好友！");
		            alert.show();
		            return;
	        	}
	        }
	        
	        for(String raccount: rooms) {
	        	if(contents.equals(raccount)) {
	        		Alert alert = new Alert(Alert.AlertType.WARNING);
		            alert.setContentText("已经加入群聊！");
		            alert.show();
		            return;
	        	}
	        }
	        // 还可以加入发送添加消息的时间
	        Message mes = new Message();
	        
	        if(contents.length() == 5) {
	        	mes.setType(MsgType.ADD_FRIEND);
		        mes.setText(contents);    //传输申请对象的账号
		        mes.setStates(ownerqq);   //复用states属性传输用户账号
		        mes.setTime(myName);      //复用time属性传输用户昵称
	        }else if(contents.length() == 4) {
	        	mes.setType(MsgType.ADD_GROUP);
	        	mes.setText(contents);
	        	mes.setStates(ownerqq);
	        }
	        	              
	        try {
	        	 Socket client = new Socket(Client_main.ip, 12345);
	        	 DataOutputStream output = new DataOutputStream(client.getOutputStream());
	        	 DataInputStream input = new DataInputStream(client.getInputStream());
	        	 Gson gson = new Gson();
	        	 String json = gson.toJson(mes);
	        	 output.writeUTF(json);
	        	 json = input.readUTF();
	        	 mes = gson.fromJson(json, Message.class);
	        	 input.close();
	        	 client.close();
	        	 
	        	 if(mes.getType() == MsgType.GROUP_FULL) {
	        		 Alert alert = new Alert(Alert.AlertType.WARNING);
			            alert.setContentText("群聊已满！");
			            alert.show();
			            content.clear(); //清空输入框
				        content.setPromptText("搜索好友或群聊"); //重新浮现提示文字
				        return;
	        	 }
	        	 
	        	 Alert alert = new Alert(Alert.AlertType.INFORMATION);
                 alert.setContentText("成功发送申请");
                 alert.show();      	 
	        }catch (IOException err) {
				err.printStackTrace();
			}	        
	        content.clear(); //清空输入框
	        content.setPromptText("搜索好友或群聊"); //重新浮现提示文字
	        	        	
	    });  
	    root.getChildren().add(btn_ok);
        
        
        //显示好友列表
        initList(root,msg);
        // 显示界面
        Scene scene = new Scene(root);
        this.setScene(scene);
        this.show();
    }
    public void Name_Pwd_Modify(String ownerId) {
        AnchorPane modifyRoot = new AnchorPane();
        Stage stage1 = new Stage(); // 创建 Stage 对象
        stage1.setScene(new Scene(modifyRoot, 640, 360));
        Image mmpic = new Image("file:image/friendlist/mmpic.jpg", 640, 360, false, false);
        BackgroundImage bgImg = new BackgroundImage(mmpic, BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.DEFAULT, BackgroundSize.DEFAULT);
        modifyRoot.setBackground(new Background(bgImg));

        ChoiceBox<String> choiceBox = new ChoiceBox<>();
        choiceBox.setStyle("-fx-background-color: #ECDFA6;");
        choiceBox.getItems().addAll("修改用户名", "修改密码");
        choiceBox.setValue("修改用户名");
        AnchorPane.setTopAnchor(choiceBox, 100.0);
        AnchorPane.setLeftAnchor(choiceBox, 290.0);
        modifyRoot.getChildren().add(choiceBox);

        TextField content = new TextField();
        // 处理输入框
        AnchorPane.setTopAnchor(content, 150.0);
        AnchorPane.setLeftAnchor(content, 290.0);
        content.setPrefWidth(194.0);
        content.setPrefHeight(30.0);
        content.setStyle("-fx-background-color: white;");
        modifyRoot.getChildren().add(content);

        Button btn_ok = new Button("确定");
        AnchorPane.setTopAnchor(btn_ok, 250.0);
        AnchorPane.setLeftAnchor(btn_ok, 370.0);
        btn_ok.setPrefWidth(80.0);
        btn_ok.setPrefHeight(30.0);
        btn_ok.setStyle("-fx-background-color: #0099FF; -fx-text-fill: white;");
        btn_ok.setOnAction(e -> {
            String selection = choiceBox.getValue();
            String contents = "";
            MsgType msgType = null;
            if (selection.equals("修改用户名")) {
                contents = content.getText().trim();
                String pattern = "[\\u4E00-\\u9FA5a-zA-Z0-9]{1,10}";
                if (Pattern.matches(pattern, contents)) {
                    msgType = MsgType.NAME_MODIFY;
                    jbl_qqName.setText(" "+contents+"\n"+"("+ownerqq+")");
                } else {//账号不合法
                    Alert alert = new Alert(Alert.AlertType.WARNING);
                    alert.setContentText("用户名为1到10位中文、字母或数字，请重新输入！");
                    alert.show();
                }
            } else if (selection.equals("修改密码")) {
                contents = content.getText().trim();
                String pattern = "[a-zA-Z0-9]{1,10}";
                if (Pattern.matches(pattern, contents)) {
                    msgType = MsgType.PWD_MODIFY;
                } else {//密码不合法
                    Alert alert = new Alert(Alert.AlertType.WARNING);
                    alert.setContentText("密码为1到10位英文字母或数字，请重新输入！");
                    alert.show();
                }
            }
            Message msg = new Message();
            msg.setType(msgType);
            msg.setUserID(Integer.parseInt(ownerqq));
            msg.setText(contents);
//            TODO
            try {           	 
            	 Socket client = new Socket(Client_main.ip, 12345);
            	 DataOutputStream output = new DataOutputStream(client.getOutputStream());
            	 Gson gson = new Gson();
            	 String json = gson.toJson(msg);
            	 output.writeUTF(json);
            	 output.close();
            	 client.close();
            	 
            }catch (IOException err) {
				// TODO: handle exception
            	err.printStackTrace();
			}
        });
        modifyRoot.getChildren().add(btn_ok);

        stage1.setResizable(false); // 设置stage不可改变大小
        stage1.setTitle("设置用户名");
        stage1.show();
    }
    public void Modify(String qqName, String ownerId) {
        Platform.runLater(() -> {
            jbl_qqName.setText(qqName + "(" + ownerId + ")");
        });
    }


    //将下线信息发送给服务端
    public void sendUnloadMsgToServer() {
        Message mes = new Message();
        mes.setUserID(Integer.parseInt(ownerqq));
        mes.setType(MsgType.UNLOAD_LOGIN);
        DataOutputStream output;
        try {
            Socket client = new Socket(Client_main.ip, 12345);
            output = new DataOutputStream(client.getOutputStream());
            Gson gson = new Gson();
            String json = gson.toJson(mes);
            output.writeUTF(json);            
            System.out.println("成功发送下线信息");
            client.close();
        } catch (IOException e) {
            System.out.println("连接服务器失败！");
            e.printStackTrace();
        }       
        System.exit(0);
    }

    //以树形结构显示全部好友列表
    public void initList(AnchorPane root,Message mes){
         rootNode = new TreeItem<>("我的好友");
         rootNode2 = new TreeItem<>("我的群聊");
        rootNode3 = new TreeItem<>("聊天");
        //String[] friends= {};
        Gson gson = new Gson();
        Hashtable<Integer, String> friends = new Hashtable<Integer, String>();
        Hashtable<Integer, String> rooms = new Hashtable<Integer, String>();
        
        TreeItem<String> chatgptNode = new TreeItem<>();
        chatgptNode.setValue("ChatGPT");
        rootNode.getChildren().add(chatgptNode);
        
        if(mes.getText()== null){//当好友列表为空时，直接返回
        }
        else {//msg是所有好友信息
        	friends = gson.fromJson(mes.getText(),hashtableType );
        	rooms = gson.fromJson(mes.getRooms(), hashtableType);
        	
        }
        //遍历数组
        for (Integer faccount : friends.keySet() ){
            TreeItem<String> childNode = new TreeItem<>();
            String fname = friends.get(faccount);
            String fAaccount = String.valueOf(faccount);
            String nodeValue = fname+"("+fAaccount+")";
            this.friends.add(fAaccount);
            
            childNode.setValue(nodeValue);
            rootNode.getChildren().add(childNode);
        }
                  
        for(Integer i : rooms.keySet()) {
        	TreeItem<String> childNode = new TreeItem<>();
        	String roomName = rooms.get(i);
        	String roomAccount = String.valueOf(i);
        	String nodeValue = roomName+"("+roomAccount+")";
        	this.rooms.add(roomAccount);
        	
        	childNode.setValue(nodeValue);
        	rootNode2.getChildren().add(childNode);
        }
        
        rootNode3.getChildren().add(rootNode);
        rootNode3.getChildren().add(rootNode2);
        
        //treeView 是根据 rootNode 构建的树形结构
        //当TreeView需要显示一个节点时，会调用单元格工厂来创建一个单元格，并将节点的数据传递给单元格进行显示
        treeView = new TreeView<String>(rootNode3);
        treeView.setCellFactory(tv -> new TreeCellRenderer(mes));
                

       //设置右键操作菜单
        ContextMenu contextMenu1 = new ContextMenu();
        ContextMenu contextMenu2 = new ContextMenu();
        MenuItem menuItem1 = new MenuItem("删除好友");
        MenuItem menuItem2 = new MenuItem("退出群聊");
        contextMenu1.getItems().add(menuItem1);
        contextMenu2.getItems().add(menuItem2);
        
        menuItem1.setOnAction(e->{
        	TreeItem<String> selectedItem = treeView.getSelectionModel().getSelectedItem();
            if (selectedItem != null) {
                TreeItem<String> parentItem = selectedItem.getParent();
                String friendaccount = null;
                if (parentItem != null) {               	
                	try {
                		Socket client = new Socket(Client_main.ip, 12345);
                    	DataOutputStream output = new DataOutputStream(client.getOutputStream());
                    	
                    	String friendInfo = selectedItem.getValue();
                        String[] array = friendInfo.split("\\(");
                        friendaccount = array[1].substring(0, array[1].length()-1);//取出好友账号
                    	                	
                    	Message del_mes = new Message();
                    	del_mes.setType(MsgType.DELETE_FRIEND);
                    	del_mes.setUserID(Integer.parseInt(ownerqq));    //本人的账号
                    	del_mes.setRoomID(Integer.parseInt(friendaccount));  //好友账号
                    	String json = gson.toJson(del_mes);
                    	
                    	output.writeUTF(json);
                    	output.close();
                    	client.close();
                	}catch (IOException err) {
                		err.printStackTrace();
					}
                	this.friends.remove(friendaccount);
                    parentItem.getChildren().remove(selectedItem); // 从父节点的子节点列表中移除选定的节点                                      
                } else {
                    treeView.getRoot().getChildren().remove(selectedItem); // 从根节点的子节点列表中移除选定的节点
                }
            }
        });
        
        menuItem2.setOnAction(e->{
        	TreeItem<String> selectedItem = treeView.getSelectionModel().getSelectedItem();
            if (selectedItem != null) {
                TreeItem<String> parentItem = selectedItem.getParent();
                String friendaccount = null;
                if (parentItem != null) {               	
                	try {
                		Socket client = new Socket(Client_main.ip, 12345);
                    	DataOutputStream output = new DataOutputStream(client.getOutputStream());
                    	
                    	String friendInfo = selectedItem.getValue();
                        String[] array = friendInfo.split("\\(");
                        friendaccount = array[1].substring(0, array[1].length()-1);//取出群聊账号
                    	                	
                    	Message del_mes = new Message();
                    	del_mes.setType(MsgType.EXIT_GROUP);
                    	del_mes.setUserID(Integer.parseInt(ownerqq));    //本人的账号
                    	del_mes.setRoomID(Integer.parseInt(friendaccount));  //好友账号
                    	String json = gson.toJson(del_mes);
                    	
                    	output.writeUTF(json);
                    	output.close();
                    	client.close();
                	}catch (IOException err) {
                		err.printStackTrace();
					}
                	this.rooms.remove(friendaccount);
                    parentItem.getChildren().remove(selectedItem); // 从父节点的子节点列表中移除选定的节点                                      
                } else {
                    treeView.getRoot().getChildren().remove(selectedItem); // 从根节点的子节点列表中移除选定的节点
                }
            }
        });
        
        treeView.setOnMouseClicked(e -> {
        	
        	//按下鼠标右键的操作
        	if (e.getButton() == MouseButton.SECONDARY) {
                TreeItem<String> selectedItem = treeView.getSelectionModel().getSelectedItem();
                
                if(selectedItem.getValue().equals("聊天") || selectedItem.getValue().equals("我的好友") || selectedItem.getValue().equals("我的群聊")) {
                	return;
                }
                
                if (selectedItem.getParent().getValue().equals("我的好友")) {
                    contextMenu1.show(treeView, e.getScreenX(), e.getScreenY());
                }else if (selectedItem.getParent().getValue().equals("我的群聊")) {
                	contextMenu2.show(treeView, e.getScreenX(), e.getScreenY());
				}
            }
        	
        	
                	
            if (e.getClickCount() == 2) {
                TreeItem<String> item = treeView.getSelectionModel().getSelectedItem();
                if (item != null && item.isLeaf()) {
                    String friendInfo = item.getValue();
                    
                    if(friendInfo.equals("ChatGPT")) {
                    	MachineChat ChatGPT = new MachineChat(userid, myName);
                    	ChatGPT.start(new Stage());
                    	return;
                    }
                    
                    String[] array = friendInfo.split("\\(");
                    String friendName = array[0];                                     //好友昵称
                    String friendaccount = array[1].substring(0, array[1].length()-1);//取出好友账号
                    
                                                                             
                    try {
                    	 //向服务器发送消息，让服务器返回需要的
                    	 Message msg = new Message();                   
                    	 msg.setType(MsgType.NEWCHAT);
                    	 msg.setText(friendaccount);               //复用text来传输好友账号
                    	 msg.setTime(ownerqq);                     //复用time来传输自己的账号
                    	 String json = gson.toJson(msg);
                    	 
                    	 Socket client = new Socket(Client_main.ip, 12345);
                         DataOutputStream output = new DataOutputStream(client.getOutputStream());
                         DataInputStream input = new DataInputStream(client.getInputStream());
                         output.writeUTF(json);
                         //output.close();
                         
                         json = input.readUTF();
                         msg = gson.fromJson(json, Message.class);
                         input.close();
                         client.close();
                         
                         if(msg.getType() == MsgType.RET_NEWCHATINFO) {
                        	 System.out.println("成功获取与："+friendName+"的初始化chat信息");
                        	 String json_id = msg.getText();
                        	 String json_names = msg.getRooms();
                        	 
                        	 Vector<Integer> users_id = gson.fromJson(json_id, vectorType2);
                        	 Vector<String> users_name = gson.fromJson(json_names, vectorType);
                        	 int roomid = msg.getRoomID();
                        	 
                        	  Chat chatframe = new Chat(userid, myName,roomid, users_id, users_name,friendName);
                        	  chatframe.start(new Stage());
                         }

                    }catch (IOException err) {
						// TODO: handle exception
                    	err.printStackTrace();
					}
                    
                }
            }
        });
        treeView.setPrefHeight(440);
        treeView.setPrefWidth(355);
        AnchorPane.setTopAnchor(treeView, 178.0);
        AnchorPane.setLeftAnchor(treeView, 0.0);
        root.getChildren().add(treeView);
    }
    //刷新在线好友列表
    public void updateOnlineFriends(Message mes) {       
        Gson gson = new Gson();
        Hashtable<Integer, String> friends = gson.fromJson(mes.getText(),hashtableType);
        Hashtable<Integer, String> rooms = gson.fromJson(mes.getRooms(), hashtableType);
        
        Iterator<TreeItem<String>> iterator = rootNode.getChildren().iterator(); 
        while(iterator.hasNext()) {
        	TreeItem<String> child = iterator.next();
        	
        	boolean exist = false;
     	   
        	if(child.getValue() == "ChatGPT") {
        		continue;
        	}
        	
     	   for (Integer faccount : friends.keySet() ){
                String fname = friends.get(faccount);
                String fAaccount = String.valueOf(faccount);
                String nodeValue = fname+"("+fAaccount+")";
                
                if(child.getValue().equals(nodeValue)) {
             	   friends.remove(faccount);
             	   exist = true;
             	   break;
                }
            }
     	    //如果已经有删除自己的好友，则将他从好友列表移除
     	   if(!exist) {
     		  String friendInfo = child.getValue();
              String[] array = friendInfo.split("\\(");
              String friendaccount = array[1].substring(0, array[1].length()-1);
              this.friends.remove(friendaccount);
     		  iterator.remove();
     	   }
        }
                 
       for(TreeItem<String> child : rootNode2.getChildren()) {
    	   for (Integer room : rooms.keySet() ){
               String rname = rooms.get(room);
               String rAaccount = String.valueOf(room);
               String nodeValue = rname+"("+rAaccount+")";
               if(child.getValue().equals(nodeValue)) {
            	   rooms.remove(room);
            	   System.out.println("rooms:"+rooms);
            	   break;
               }
           }
       }
       
       for(Integer faccount : friends.keySet()) {
    	   TreeItem<String> childNode = new TreeItem<>();
           String fname = friends.get(faccount);
           String fAaccount = String.valueOf(faccount);
           String nodeValue = fname+"("+fAaccount+")";
           this.friends.add(fAaccount);
           
           childNode.setValue(nodeValue);
           rootNode.getChildren().add(childNode);
       }
       
       
       for(Integer room : rooms.keySet()) {
    	   TreeItem<String> childNode = new TreeItem<>();
           String rname = rooms.get(room);
           String rAaccount = String.valueOf(room);
           String nodeValue = rname+"("+rAaccount+")";
           this.rooms.add(rAaccount);          
           childNode.setValue(nodeValue);
           rootNode2.getChildren().add(childNode);
       }             
       Platform.runLater(() -> {
    	   this.treeView.refresh();
    	   this.treeView.setCellFactory(tv -> new TreeCellRenderer(mes));
    	});
       
    }
    //修改用户名逻辑
}